package com.xiaoyu.lanling.feature.board.data

import `in`.srain.cube.request.JsonData
import `in`.srain.cube.request.RequestDefaultHandler
import `in`.srain.cube.views.list.PagedListDataModelWithRequestTag
import com.xiaoyu.base.net.RequestCreator
import com.xiaoyu.lanling.event.board.BoardListEvent
import com.xiaoyu.lanling.event.board.BoardTop3Event
import com.xiaoyu.lanling.feature.board.model.BoardItem
import kotlin.math.min

/**
 * tag 区分开 四个页面的数据，底层会根据 tag 来分别处理
 */
class BoardListViewData constructor(val reqTag: Any, val url: String, val boardType: String, val timeType: String) : PagedListDataModelWithRequestTag<BoardItem, Any>() {

    override fun doQueryData() {

        RequestCreator.create(BoardListEvent::class.java)
                .setRequestUrl(url)
                .addQueryData("boardType", boardType)
                .addQueryData("timeType", timeType)
                .appendQueryDataTo(listPageInfo)
                .setRequestHandler(object : RequestDefaultHandler<BoardListEvent, JsonData>() {

                    override fun processOriginData(originData: JsonData): BoardListEvent {
                        val rawData = originData.optJson("data")
                        val isFirstPage = listPageInfo.isFirstPage
                        val preLen = if (isFirstPage) 0 else listPageInfo.dataList.size
                        val list = mutableListOf<BoardItem>()

                        for ((i, item) in rawData.toList().withIndex()) {
                            list.add(BoardItem(i + preLen + 1, item))
                        }

                        var rest = mutableListOf<BoardItem>()
                        // first page , first three items
                        if (isFirstPage) {

                            val top3List = mutableListOf<BoardItem>()
                            for (i in 0 until min(3, list.size)) {
                                top3List.add(list[i])
                            }

                            BoardTop3Event(requestTag, top3List).post()

                            if (list.size > 3) {
                                rest = list.subList(3, list.size)
                            }
                        } else {
                            rest = list
                        }
                        updateResult(rawData, rest)

                        return BoardListEvent(requestTag)
                    }

                    override fun onRequestFinish(data: BoardListEvent) {
                        data.post()
                    }
                })
                .enqueue()
    }

    override fun getRequestTag(): Any {
        return reqTag
    }
}